<template>
  <div class="app-container">
    <el-form ref="form"
             :model="form"
             :rules="rules"
             :label-position="labelPosition"
             class="register-form">
      <el-row :gutter="40">
        <el-col :span="8">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="reportNo" label="报告文号">
                <el-input v-model="form.reportNo" type="text" auto-complete="off" placeholder="请输入报告文号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="customerName" label="客户名称（被审验单位名称）">
                <el-input v-model="form.customerName" type="text" auto-complete="off" placeholder="请输入客户名称（被审验单位名称）" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="customerBusinessLicense" label="客户营业执照号">
                <el-input v-model="form.customerBusinessLicense" type="text" auto-complete="off" placeholder="请输入客户营业执照号" />
              </el-form-item>
            </el-col>
           <!-- <el-col :span="12">
              <el-form-item prop="administrativeDivision" label="事务所行政区划">
                <el-input v-model="form.administrativeDivision" type="text" auto-complete="off" placeholder="请输入事务所行政区" />
              </el-form-item>
            </el-col>-->
           <!-- <el-col :span="12">
              <el-form-item prop="hasSecurities" label="是否具有证券资格">
                <el-select v-model="form.hasSecurities" placeholder="请选择">
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
            </el-col>-->
            <el-col :span="12">
              <el-form-item prop="isSecuritiesBusiness" label="是否属于证券业务">
                <el-select v-model="form.isSecuritiesBusiness" placeholder="请选择">
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="firstBusinessTime" label="首次承接业务时间">
                <el-date-picker
                  v-model="form.firstBusinessTime"
                  type="date"
                  placeholder="请选择">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="officeRemarks" label="备注">
                <el-input v-model="form.officeRemarks" type="text" auto-complete="off" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button
              :loading="loading"
              size="medium"
              type="primary"
              @click.native.prevent="handleSubmit(1)"
            >
              <span v-if="!loading">提 交</span>
              <span v-else>提 交 中...</span>
            </el-button>
            <!--<el-button
              :loading="loading"
              size="medium"
              type="primary"
              @click.native.prevent="handleSubmit('1')"
            >
              <span v-if="!loading">保 存 草 稿</span>
              <span v-else>保 存 中...</span>
            </el-button>-->
            <el-button
              size="medium"
              type="default"
              @click.native.prevent="handleGoBack"
            >
              <span>返 回</span>
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item prop="reportType" label="报备类型">
                <el-select v-model="form.reportType"
                           placeholder="请选择"
                           clearable
                           filterable
                           @change="reportTypeChange"
                >
                  <el-option
                    v-for="(item,index) in reportTypeOption"
                    :key="index+'z'"
                    :label="item.dictLabel"
                    :value="item.dictValue" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="opinionType" label="意见类型(可填可选)">
                <el-select v-model="form.opinionType"
                           placeholder="请选择"
                           clearable
                           filterable
                           @blur="selectBlur"
                           @clear="selectClear"
                           @change="selectChange"
                >
                  <el-option
                    v-for="(item,index) in opinionTypeOption"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictValue" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="auditYear" label="审计年度">
                <!--<el-date-picker
                  v-model="form.auditYear"
                  type="year"
                  placeholder="请选择"
                  value-format="yyyy">
                </el-date-picker>-->
                <el-input v-model="form.auditYear" type="text" auto-complete="off" placeholder="请输入审计年度" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="reportTime" label="报告日期">
                <el-date-picker
                  v-model="form.reportTime"
                  type="date"
                  placeholder="请输入报告日期"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
         <!-- <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item
                prop="reportCode"
                label="报备编码"
              >
                <el-input v-model="form.reportCode" type="text" auto-complete="off" placeholder="请输入报备编码"/>
              </el-form-item>
            </el-col>-->

           <!-- <el-col :span="6">
              <el-form-item prop="filingYear" label="报备年度">
                <el-date-picker
                  v-model="form.filingYear"
                  type="year"
                  placeholder="请选择">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="filingTime" label="报备日期">
                <el-date-picker
                  v-model="form.filingTime"
                  type="date"
                  placeholder="请选择">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="reportStatus" label="报备状态">
                <el-select v-model="form.reportStatus" placeholder="请选择">
                  <el-option label="已报备" value="已报备" />
                  <el-option label="未报备" value="未报备" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>-->
          <el-row :gutter="20">
            <!--<el-col :span="6">
              <el-form-item prop="uploadTime" label="上传时间">
                <el-date-picker
                  v-model="form.uploadTime"
                  type="datetime"
                  placeholder="请选择">
                </el-date-picker>
              </el-form-item>
            </el-col>-->
            <el-col :span="6">
              <el-form-item prop="chargeAmount" label="收费金额（元）">
                <el-input-number v-model="form.chargeAmount" controls-position="right" :min="0" :precision="2" :max="9999999999" auto-complete="off" placeholder="请输入收费金额" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="capitalVerificationAmount" label="验资金额（元）">
                <el-input-number v-model="form.capitalVerificationAmount" controls-position="right" :min="0" :precision="2" :max="9999999999" auto-complete="off" placeholder="请输入验资金额" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="capitalVerificationCurrency" label="验资币种">
                <el-select
                  v-model="form.capitalVerificationCurrency"
                  placeholder="请选择"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="(item,index) in currencyTypeOption"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictValue" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item prop="placeOfIncorporation"
                            label="公司注册地"
              >
                <el-select
                  v-model="form.placeOfIncorporation"
                  placeholder="请选择"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="(item,index) in addressPronOption"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictLabel" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="businessAddress"
                            label="业务所在地"
              >
                <el-select
                  v-model="form.businessAddress"
                  placeholder="请选择"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="(item,index) in addressPronOption"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictLabel" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-for="(item, index) in form.assuranceBusinessDataRegisterSignatures" :key="item.registerId">
            <el-col :span="6">
              <el-form-item
                :label="`签字注会${index+1}证书号`"
                :prop="'assuranceBusinessDataRegisterSignatures[' + index + '].registrationCertificateNo'"
                :rules="form.assuranceBusinessDataRegisterSignatures[index] && form.assuranceBusinessDataRegisterSignatures[index].registrationCertificateRules ? form.assuranceBusinessDataRegisterSignatures[index].registrationCertificateRules:{}"
              >
                <el-input v-model="item.registrationCertificateNo" type="text" auto-complete="off" placeholder="请输入签字注师证号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                :label="`签字注册会计师${index+1}`"
                :prop="'assuranceBusinessDataRegisterSignatures[' + index + '].registrantName'"
                :rules="form.assuranceBusinessDataRegisterSignatures[index]&&form.assuranceBusinessDataRegisterSignatures[index].registrantNameRules?form.assuranceBusinessDataRegisterSignatures[index].registrantNameRules:{}"
              >
                <el-input v-model="item.registrantName" type="text" auto-complete="off" placeholder="请输入签字注师姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item v-if="index===0 && form.assuranceBusinessDataRegisterSignatures.length < 4" label="增加会计师">
                <span class="btnPosition" @click.prevent="addData"><i class="el-icon-plus"></i></span>
              </el-form-item>
              <el-form-item v-if="index>1" label="删除会计师">
                <span class="btnPosition" @click.prevent="removeData(item)"><i class="el-icon-minus"></i></span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
  import { preUploadSave,saveDraft,getAssurance } from "@/api/system/assurance";
  export default {
    name: "AssuranceAdd",
   data() {
      return {
        businessId: this.$route.query.businessId, // 传过来的 id
        labelPosition: "top",
        reportTypeOption: [], // 报备类型
        currencyTypeOption: [], // 验资币种
        opinionTypeOption: [], // 意见类型
        addressPronOption:[],//业务所在地，公司注册地 数据
        form: {
          assuranceBusinessDataRegisterSignatures:[
            {
              registrantName: '',
              registrationCertificateNo: '',
              registrantNameRules: {},
              registrationCertificateRules: {}
            },
            {
              registrantName: '',
              registrationCertificateNo: '',
              registrantNameRules: {},
              registrationCertificateRules: {}
            },
          ]
        },
        rules: {}, // 预上传 表单规则： 必填/选填
        loading: false,
        redirect: undefined,
        targetResOBJ:''
      };
    },
    deactivated () { //清除keep-alive的缓存
      this.$destroy(true)
    },
     async created() {
      if(this.businessId){
        const response = await getAssurance(this.businessId)
        if(response.msg && response.msg == "无权限"){
          this.$message({
            message: "无权限!",
            type: 'error'
          });
          this.$router.push("/assurance/list")
        }else {
          this.form = response.data;
        }
      }
       this.getDicts("report_type").then(response => {
         // 报备类型
         this.reportTypeOption = response.data;
       });
       this.getDicts("currency").then(response => {
         // 验资币种
         this.currencyTypeOption = response.data
       });
       this.getDicts("type_of_opinion").then(response => {
         // 意见类型
         this.opinionTypeOption = response.data
       });
       this.getDicts("business_address_pron").then(response => {
         // 意见类型
         this.addressPronOption = response.data
       });

       const res = await this.getConfigKey("office.preload.config")
      let preConfig = JSON.parse(res.msg);
      this.targetResOBJ = res.msg;
        // 读取预上传 接口并 转换 必填：'0'true 选填：'1'false
        /** 值转换 必填：true 选填：false */
        for(let key in preConfig){
          if(!Array.isArray(preConfig[key])) {
            // 非数组 对象.属性 = true/false
            preConfig[key] === '0' ? preConfig[key] = true : preConfig[key] = false
          }else{
            // 处理 assuranceBusinessDataRegisterSignatures 数组
            preConfig.assuranceBusinessDataRegisterSignatures.forEach((item,index) => {
              item.registrantName === '0' ? item.registrantName = true : item.registrantName = false
              item.registrationCertificateNo === '0' ? item.registrationCertificateNo = true : item.registrationCertificateNo = false
            })
          }
        }
          let that = this;
          that.rules = {
              administrativeDivision: [{ required: preConfig.administrativeDivision, trigger: "blur", message: "事务所行政区划不能为空" }], // 事务所行政区划 200
              hasSecurities: [{ required: preConfig.hasSecurities, trigger: "change", message: "是否具有证券资格不能为空" }], // 是否具有证券资格 5
              customerName: [{ required: preConfig.customerName, trigger: "blur", message: "客户名称（被审验单位名称）不能为空" }], // 客户名称（被审验单位名称） 100
              customerBusinessLicense: [{ required: preConfig.customerBusinessLicense, trigger: "blur", message: "客户营业执照号不能为空" }], // 客户名称（被审验单位名称） 100
              reportType: [{ required: preConfig.reportType, trigger: "change", message: "报备类型不能为空" }], // 报备类型 50
              auditYear: [{ required: preConfig.auditYear, trigger: "blur", message: "审计年度不能为空" }], // 审计年度 20
              filingYear: '', // 报备年度 20
              reportNo: [{ required: preConfig.reportNo, trigger: "blur", message: "报告文号不能为空" }], // 报告文号 50
              //chargeAmount: [{ required: preConfig.chargeAmount, trigger: "blur", message: "收费金额不能为空" }], // 收费金额 20
              isSecuritiesBusiness: [{ required: preConfig.isSecuritiesBusiness, trigger: "change", message: "是否属于证券业务不能为空" }], // 是否属于证券业务 5
              opinionType: [{ required: preConfig.opinionType, trigger: "change", message: "意见类型不能为空" }], // 意见类型 10
              reportTime: [{ required: preConfig.reportTime, trigger: "blur", message: "报告日期不能为空" }],
              businessAddress: [{ required: true, trigger: "blur", message: "业务所在地不能为空" }],
              placeOfIncorporation: [{ required: true, trigger: "blur", message: "公司注册地不能为空" }],
              capitalVerificationAmount: [{ required: preConfig.capitalVerificationAmount, trigger: "blur", message: "验资金额不能为空" }],
              capitalVerificationCurrency: [{ required: preConfig.capitalVerificationCurrency, trigger: "change", message: "验资币种不能为空" }],
              firstBusinessTime: [{ required: preConfig.firstBusinessTime, trigger: "change", message: "首次承接业务时间不能为空" }],
          }
          that.form.assuranceBusinessDataRegisterSignatures[0].registrantNameRules = {required: preConfig.assuranceBusinessDataRegisterSignatures[0].registrantName, message: '签字注师姓名不能为空', trigger: 'blur'};
          that.form.assuranceBusinessDataRegisterSignatures[1].registrantNameRules = {required: preConfig.assuranceBusinessDataRegisterSignatures[1].registrantName, message: '签字注师姓名不能为空', trigger: 'blur'};
          that.form.assuranceBusinessDataRegisterSignatures[0].registrationCertificateRules = {required: preConfig.assuranceBusinessDataRegisterSignatures[0].registrationCertificateNo, message: '签字注师证号不能为空', trigger: 'blur'};
          that.form.assuranceBusinessDataRegisterSignatures[1].registrationCertificateRules = {required: preConfig.assuranceBusinessDataRegisterSignatures[1].registrationCertificateNo, message: '签字注师证号不能为空', trigger: 'blur'};

    },
    methods: {
      selectBlur(e) {
        // 意见类型
        if (e.target.value !== '') {
          this.form.opinionType = e.target.value + '(其他)';
          this.$forceUpdate()
        }
      },
      selectClear() {
        this.form.opinionType = ''
        this.$forceUpdate()
      },
      selectChange(val) {
        this.form.opinionType = val
        this.$forceUpdate()
      },
      reportTypeChange(val) {
        let targetRes = JSON.parse(this.targetResOBJ)
        this.verityType(val);
       /* if(this.businessId) {
          if (val != "" && val != null && val != undefined) {
            if (val == "验资业务") {
              this.rules.opinionType = [{required: false, trigger: "change", message: "意见类型不能为空"}]
              this.rules.capitalVerificationAmount = [{required: true, trigger: "blur", message: "验资金额不能为空"}]
              this.rules.capitalVerificationCurrency = [{required: true, trigger: "change", message: "验资币种不能为空"}]
            } else {
              this.rules.opinionType = [{required: true, trigger: "change", message: "意见类型不能为空"}]
              this.rules.capitalVerificationAmount = [{required: false, trigger: "blur", message: "验资金额不能为空"}]
              this.rules.capitalVerificationCurrency = [{required: false, trigger: "change", message: "验资币种不能为空"}]

            }
            if (val == "验资业务" || val == "专项审计业务" || val == "专项审计业务") {
              this.rules.auditYear = [{required: false, trigger: "blur", message: "审计年度不能为空"}] // 审计年度 20
            } else {
              this.rules.auditYear = [{required: true, trigger: "blur", message: "审计年度不能为空"}] // 审计年度 20
            }
          } else {
            this.rules.opinionType = [{
              required: targetRes.opinionType == "0" ? true : false,
              trigger: "change",
              message: "意见类型不能为空"
            }]
            this.rules.capitalVerificationAmount = [{
              required: targetRes.capitalVerificationAmount == "0" ? true : false,
              trigger: "blur",
              message: "验资金额不能为空"
            }]
            this.rules.capitalVerificationCurrency = [{
              required: targetRes.capitalVerificationCurrency == "0" ? true : false,
              trigger: "change",
              message: "验资币种不能为空"
            }]
            this.rules.auditYear = [{
              required: targetRes.auditYear == "0" ? true : false,
              trigger: "blur",
              message: "审计年度不能为空"
            }] // 审计年度 20
          }
        }*/
          this.$forceUpdate()
      },
      //通过报备类型校验必填字段
      verityType(val){
        if(this.businessId) {
          if (val != "" && val != null && val != undefined) {
            if (val == "验资业务") {
              this.rules.opinionType = [{required: false, trigger: "change", message: "意见类型不能为空"}]
              this.rules.capitalVerificationAmount = [{required: true, trigger: "blur", message: "验资金额不能为空"}]
              this.rules.capitalVerificationCurrency = [{required: true, trigger: "change", message: "验资币种不能为空"}]
            } else {
              this.rules.opinionType = [{required: true, trigger: "change", message: "意见类型不能为空"}]
              this.rules.capitalVerificationAmount = [{required: false, trigger: "blur", message: "验资金额不能为空"}]
              this.rules.capitalVerificationCurrency = [{required: false, trigger: "change", message: "验资币种不能为空"}]

            }
            if (val == "验资业务" || val == "专项审计业务" || val == "专项审计业务") {
              this.rules.auditYear = [{required: false, trigger: "blur", message: "审计年度不能为空"}] // 审计年度 20
            } else {
              this.rules.auditYear = [{required: true, trigger: "blur", message: "审计年度不能为空"}] // 审计年度 20
            }
          } else {
            this.rules.opinionType = [{
              required: targetRes.opinionType == "0" ? true : false,
              trigger: "change",
              message: "意见类型不能为空"
            }]
            this.rules.capitalVerificationAmount = [{
              required: targetRes.capitalVerificationAmount == "0" ? true : false,
              trigger: "blur",
              message: "验资金额不能为空"
            }]
            this.rules.capitalVerificationCurrency = [{
              required: targetRes.capitalVerificationCurrency == "0" ? true : false,
              trigger: "change",
              message: "验资币种不能为空"
            }]
            this.rules.auditYear = [{
              required: targetRes.auditYear == "0" ? true : false,
              trigger: "blur",
              message: "审计年度不能为空"
            }] // 审计年度 20
          }
        }
      },
      handleSubmit(status) {
        this.verityType(this.form.reportType);
        this.$refs.form.validate(valid => {
          if (valid) {
            this.loading = true;
            if(status == 0){
              saveDraft(this.form).then(
                response => {
                  this.$confirm('保存成功', '提示', {
                    confirmButtonText: '返回',
                    showClose: false,
                    showCancelButton: false,
                    type: 'success'
                  }).then(() => {
                      this.loading = false ;
                      this.$store.dispatch("tagsView/delView", this.$route);
                    this.colseCurWin();
                  });
                }
              );
            }else{
              preUploadSave(this.form).then(
                response => {
                  this.$confirm('保存成功', '提示', {
                    confirmButtonText: '返回',
                    showClose: false,
                    showCancelButton: false,
                    type: 'success'
                  }).then(() => {
                    this.loading = false ;
                    this.$store.dispatch("tagsView/delView", this.$route);
                    this.colseCurWin();
                  });

                }
              ).catch((error)=>{
                this.loading = false ;
              });
            }
          }
        });
      },
      handleGoBack() {
          this.$store.dispatch("tagsView/delView", this.$route);
        this.colseCurWin();
      },
      addData() {
        this.form.assuranceBusinessDataRegisterSignatures.push({
          registrantName: '',
          registrationCertificateNo: '',
          registrantNameRules: {required: true, message: '签字注师姓名不能为空', trigger: 'blur'},
          registrationCertificateRules: {required: true, message: '签字注师证号不能为空', trigger: 'blur'}
        },);
      },
      removeData(item) {
        let index = this.form.assuranceBusinessDataRegisterSignatures.indexOf(item)
        if (index !== -1) {
          this.form.assuranceBusinessDataRegisterSignatures.splice(index, 1)
        }
      },
    }
  };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  ::v-deep .el-form-item__label{
    position: relative;
    font-size: 15px;
  }
  ::v-deep .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before {
    content: '';  // 去掉 * 号
  }
  ::v-deep .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:after {
    content: '*';  // 后置 * 号
    color: #ff4949;
    margin-right: 4px;
    right: -15px;
    top: 2px;
    position: absolute;
  }
  ::v-deep .el-input__inner{
    &::-webkit-input-placeholder {
      font-size: 13px;
    }
  }
  ::v-deep .el-date-editor.el-input, ::v-deep .el-select{
    width: 100%;
  }
  .btnPosition{
    display: inline-block;
    text-align: center;
    height: 36px;
    line-height: 36px;
    padding: 0 16px;
    cursor: pointer;
    border-radius: 4px;
    color: #848ae3;
    font-size: 18px;
    font-weight: 900;
    border: 1px solid rgba(132,138,227,.3);
    background: #fff;
    &:hover{
      border: 1px solid rgba(132,138,227,.9);
    }
  }
  .poBtn{
    margin-top: 50px;
    display: block;
    text-align: center
  }
</style>
